package map;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author Justin Parker
 * @Date 2024/7/22 0022 17:01
 * @Version 1.0
 */
public class MapDemo03 {
    static int i =0;
    public static void main(String[] args) throws InterruptedException {
        //HashMap线程不安全
        HashMap<String,Integer> map1 = new HashMap<>();
        map1.put("A",40);
        map1.put("B",50);
        map1.put("C",60);
        map1.put("D",70);
        System.out.println("map1:"+map1);

        //将线程不安全的map对象转换为线程安全的的map对象
        Map<String, Integer> stringStringMap = Collections.synchronizedMap(map1);

        //LinkedHashMap(可以记录Key的添加顺序)
        LinkedHashMap<String,Integer> map2 = new LinkedHashMap<>();
        map2.put("D",100);
        map2.put("C",80);
        map2.put("B",60);
        map2.put("A",40);
        System.out.println("map2:"+map2);

        //TreeMap(这个map可以对添加的元素进行排序，可以需要实现Comparable接口)
        //或者构建TreeMapp对象时，指定Comparator对象设计排序逻辑
        TreeMap<Integer,String> map3 = new TreeMap<>();
        map3.put(40,"A");
        map3.put(30,"B");
        map3.put(15,"C");
        map3.put(70,"D");
        System.out.println("map3:"+map3);

        //线程安全的HashMap(可以在并发环境下使用)
        ConcurrentHashMap<String,Integer> map4 = new ConcurrentHashMap<>();
        map4.put("A",40);
        map4.put("B",50);
        map4.put("C",60);
        map4.put("D",70);
        System.out.println("map4:"+map4);

//        for (;i < 10; i++) {
//            new Thread(()->{
//               for (int j = 0; j < 10; j++){
//                   map1.put(i+" "+j, Thread.currentThread().getName());
//               }
//            }).start();
//        }
//        Thread.sleep(5000);
//        System.out.println(map1.size());
//
//        map1.forEach((k,v)->{
//            System.out.println(k+" "+v);
//        });
    }
}
